#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   GameInit
@Time    :   2023/03/11 15:15:52
@author  :   Eval
@Version :   1.0
@Describe:   初始化游戏,以及保存游戏中所使用的缓存等
'''
import pygame
from lib.scripts.GC import *
from lib.scripts.MapLogic import *

class GameInit:
    def __init__(self) -> None:
        self.anim = 0
        self.delay = 100
        # 缓存当前楼层的图块对象
        self.FBCache:dict[BlockSprite] = {}
        self.__loadSource()

    def __loadSource(self):
        """根据传进来的资源配置文件加载游戏精灵"""
        for img in GC.GC_MapImages:
            # 加载图片
            GC.GC_GameSurfaceCache[img["name"].split(".")[0]] = GC.loadSurface(img["name"])

    def clearCache(self):
        """清空当前楼层缓存,会重新渲染所有的缓存,谨慎使用"""
        self.FBCache.clear()

    def delCachePos(self,x,y):
        """删除某个坐标的缓存,直接变为地板,不用遍历资源,效率最高,无法指定新的图块缓存,不推荐使用"""
        pos:BlockSprite = self.getCachePos(x,y)
        if pos is  None:
            return 
        self.FBCache[f"{x}-{y}"] = BlockSprite(GC.loadSurface("terrains"),{"animMax":0,"type":"null","key":0,"index":0})

    def modifyCachePos(self,x,y,BKey:str):
        """删除某个坐标的缓存,BKey为资源素材对应的索引,根据这个索引得到素材将其渲染到这个点,需要遍历资源,效率较低,但是推荐使用"""
        pos:BlockSprite = self.getCachePos(x,y)
        if pos is  None:
            return 
        block = None
        for s in GC.GC_SourceMgr:
            if str(s) == str(BKey):
                block = GC.GC_SourceMgr[s]
                break
        self.FBCache[f"{x}-{y}"] = BlockSprite(GC.GC_GameSurfaceCache.get(block["type"]),block)

    def getCachePos(self,x,y):
        """返回指定坐标点的缓存图块"""
        return self.FBCache.get(f"{x}-{y}")

class BlockSprite:
    """
    @param {*}: surface 图像, 从 GC的 GameSurfaceCache 缓存字典中取出来
    @param {*}: GBlock 图块的资源数据 从 Source.json里面取出来
    @remark: 加载图块精灵
    return: None
    """
    def __init__(self,surface:pygame.surface,GBlock:dict,mg:MapMgr=None) -> None:
        self.image = surface
        self.animMax = int(GBlock["animMax"])
        self.animIndex = 0
        self.type = GBlock["type"]
        self.name = GBlock.get("name") or "null"
        self.key = int(GBlock["key"])
        self.index = int(GBlock["index"])
        self.trigger = GBlock.get("trigger") or "null"
        self.canPass = GBlock.get("canPass") or "null"
        self.w = 32
        self.h = 32
        # 记录当前精灵的坐标
        self.objectName = [0,0]
        # 是否存活
        self.active = True
        # 是否执行动画,用于开门事件
        self.isPlayAnim = False
        self.mapLogic:MapMgr = mg


    def update(self,scene,x,y):
        # 如果触发器不是openDoor的图块才执行动画
        if self.trigger!= "openDoor":
            if self.animMax >0 and scene.GInit.delay % 20 == 0:
                self.animIndex = (self.animIndex+1) % self.animMax
        else:
            if self.isPlayAnim:
                if self.animMax >0  and scene.GInit.delay % 2 == 0:
                    self.animIndex += 1
                    if self.animIndex == self.animMax:
                        self.mapLogic.updataFPoint(int(self.objectName[0]),int(self.objectName[1]),0)
                        self.animIndex +=1
                        self.isPlayAnim = False

        scene.win.blit(self.image,(x,y),(self.animIndex *self.w,self.h*self.index,self.w,self.h))

    def __str__(self) -> str:
        return f"名称:{self.name},坐标:{self.objectName},类型:{self.type}"
